﻿using System.Security.Cryptography;
using System.Text;


namespace ConsoleApp.Service
{
    public class EncryptHelper
    {
        private byte[] key;
        private int length;

        public EncryptHelper(string key)
        {
            this.key = Encoding.UTF8.GetBytes(key);
            length = 16;
        }

        private Func<string, string> unpad = (data) =>
        {
            int length = int.Parse(data.Substring(data.Length - 2));
            return data.Substring(0, data.Length - length);
        };

        private string fillMethod(string aes_str)
        {
            int length = aes_str.Length;
            int padding_length = this.length - length % this.length;
            char padding_character = (char)padding_length;

            for (int i = 0; i < padding_length; i++)
            {
                aes_str += padding_character;
            }

            return aes_str;
        }

        public string encrypt(string encrData)
        {
            encrData = fillMethod(encrData);

            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = key;
                aesAlg.Mode = CipherMode.ECB;
                aesAlg.Padding = PaddingMode.None;

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                byte[] encryptedData;

                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        byte[] data = Encoding.UTF8.GetBytes(encrData);
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();
                        encryptedData = ms.ToArray();
                    }
                }

                return Convert.ToBase64String(encryptedData);
            }
        }

        public string decrypt(string decrData)
        {
            byte[] encryptedData = Convert.FromBase64String(decrData);

            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = key;
                aesAlg.Mode = CipherMode.ECB;
                aesAlg.Padding = PaddingMode.None;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                string decryptedData;

                using (var ms = new MemoryStream(encryptedData))
                {
                    using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (var sr = new StreamReader(cs))
                        {
                            decryptedData = sr.ReadToEnd();
                        }
                    }
                }

                return unpad(decryptedData);
            }
        }
    }
}
